const typeis = v => Object.prototype.toString.call(v).slice(8, -1).toLocaleLowerCase();
const is = (v, type) => typeis(v) === type.toLocaleLowerCase();
const typemap = {};

typemap['String'] = '';
typemap['Number'] = 0;

const only = (data, config) => {
  if (!is(config, 'object')) throw new Error('config must be a object');

  const res = {};
  const configKeys = Object.keys(config);

  for (let i = 0; i < configKeys.length; i += 1) {
    const key = configKeys[i];

    if (is(data[key], 'object')) continue;

    const type = config[key];
    const defaultValue = typemap[type];

    res[key] = data[key] ? data[key] : defaultValue;
    
    if (!is(data[key], config[key].toLocaleLowerCase())) throw new Error(`${key} is invalid type`);
  }

  return res;
}

module.exports = only;
